var trendlineData = new Array();
var trendlineDate = new Array();
function svgGen(posX, posY, value, total, R) {
    var center;
    posX += R;
    posY += R;
    var alpha = 360 / total * value,
            a = (90 - alpha) * Math.PI / 180,
            x = posX + R * Math.cos(a),
            y = posY - R * Math.sin(a),
            path;
    if (total == value) {
        path = "M " + posX + ", " + posY + " m " + -R + ", 0 a " + R + "," + R +
                " 0 1,0 " + (2 * R) + ",0 a " + R + "," + R + " 0 1,0 -" + (2 * R) + ",0";
    } else {
        if (alpha > 180) {
            center = 1;
        } else {
            center = 0;
        }
        path = "M" + posX + "," + (posY - R) + " A" + R + "," + R + "," + 0 +
                "," + center + "," + 1 + "," + x + "," + y;
    }
    return path;
}

function socialGraph(element, posX, posY, strokeColor, radius, percent) {
    var paper = Raphael(element, radius * 2 + 4, radius * 2 + 4);
    var c = paper.path(svgGen(3 + posX, 3 + posY, 100, 100, radius - 3))
            .attr({stroke: "#e5e5e5", opacity: 1, "stroke-width": 6});
    var d = paper.path(svgGen(3 + posX, 3 + posY, percent, 100, radius - 3))
            .attr({stroke: strokeColor, opacity: 1, "stroke-width": 6});
}

var colors = new Array();
colors[2] = "#66C36B";
colors[1] = "#000000";
colors[0] = "#EA4037";
Raphael.fn.sentiment = function(cx, cy, r, values, labels, stroke) {
    var paper = this,
            rad = Math.PI / 180,
            chart = this.set();
    function sector(cx, cy, r, startAngle, endAngle, params) {
        var x1 = cx + r * Math.cos(-startAngle * rad),
                x2 = cx + r * Math.cos(-endAngle * rad),
                y1 = cy + r * Math.sin(-startAngle * rad),
                y2 = cy + r * Math.sin(-endAngle * rad);
        return paper.path(["M", cx, cy, "L", x1, y1, "A", r, r, 0, +(endAngle - startAngle > 180), 0, x2, y2, "z"]).attr(params);
    }
    var angle = 0,
            total = 0,
            start = 0,
            process = function(j) {
        var value = values[j],
                angleplus = 180 * value / total,
                popangle = angle + (angleplus / 2),
                color = colors[j],
                //color = Raphael.hsb(start, .75, 1),
                ms = 500,
                delta = 30,
                //bcolor = Raphael.hsb(start, 1, 1),
                bcolor = colors[j],
                p = sector(cx, cy, r, angle, 180, {fill: "90-" + bcolor + "-" + color, stroke: false, "stroke-width": 0}),
        txt = paper.text(cx + (r + delta + 55) * Math.cos(-popangle * rad), cy + (r + delta + 25) * Math.sin(-popangle * rad), labels[j]).attr({fill: bcolor, stroke: "none", opacity: 0, "font-size": 20});
        angle += angleplus;
        chart.push(p);
        chart.push(txt);
        start += .1;
    };
    for (var i = 0, ii = values.length; i < ii; i++) {
        total += values[i];
    }
    for (i = 0; i < ii; i++) {
        process(i);
    }
    return chart;
};
var percent = 0;
$(document).ready(function() {
    inte = setInterval('increasePercent()', 5);
});
function increasePercent() {
    percent += 1;
    if ($('#graph0').attr('percent') > percent)
        $('#graph0').find('path').last().attr('d', svgGen(5, 5, percent, 100, 45));
    if ($('#graph1').attr('percent') > percent)
        $('#graph1').find('path').last().attr('d', svgGen(5, 5, percent, 100, 45));
    if ($('#graph2').attr('percent') > percent)
        $('#graph2').find('path').last().attr('d', svgGen(5, 5, percent, 100, 45));
    if ($('#graph3').attr('percent') > percent)
        $('#graph3').find('path').last().attr('d', svgGen(5, 5, percent, 100, 45));
    if (percent == 100)
        clearInterval(inte);
}

function loadTrendLine() {
    streamId = window.location.href.split('#')[1].split('/')[1];
    dateFrom = $('#selected_date').attr('datefrom');
    dateTo = $('#selected_date').attr('dateto');
    language = 2;
    var pl = new SOAPClientParameters();
    pl.add("typedata", "filter");
    pl.add("streamId", streamId);
    pl.add("dateFrom", dateFrom);
    pl.add("dateTo", dateTo);
    pl.add("language", language);
    SOAPClient.invoke("http://localhost/buzzPulse/m/", "getTrendlineData", pl, true, trendLoadCompleted);
}

function trendLoadCompleted(r) {
    if (r) {
        total = r.total;
        $('#total-number-of-mentions .number').html(nFormatter(total));
        trendlineDate = r.date.split(',');
        trendlineData = _trendlineData = r.data.split(',');
        for (i = 0; i < _trendlineData.length; i++) {
            trendlineData[i] = parseInt(_trendlineData[i]);
        }
        $(function() {
            $('#widget-trendline').highcharts({
                chart: {
                    type: 'areaspline',
                    spacingBottom: 0
                },
                title: {
                    text: ''
                },
                subtitle: {
                    text: '',
                    floating: true,
                    align: 'right',
                    verticalAlign: 'bottom',
                    y: 15
                },
                legend: {
                    layout: 'vertical',
                    align: 'left',
                    verticalAlign: 'top',
                    x: 150,
                    y: 100,
                    floating: true,
                    borderWidth: 1,
                    backgroundColor: 'transparent'
                },
                xAxis: {
                    gridLineWidth: 0,
                    tickWidth: 0,
                    lineWidth: 0,
                    categories: trendlineDate
                },
                yAxis: {
                    title: {
                        text: ''
                    },
                    showFirstLabel: false,
                    gridLineColor: '#C0C0C0',
                    gridLineDashStyle: 'Dot',
                    gridLineWidth: 0,
                    labels: {
                        formatter: function() {
                            return this.value / 1000 + 'k';
                        }
                    },
                    endOnTick: false,
                    maxPadding: 0.1
                },
                tooltip: {
                    formatter: function() {
                        return '<b>' + this.series.name + '</b><br/>' +
                                this.x + ': ' + this.y;
                    }
                },
                plotOptions: {
                    area: {
                        fillOpacity: 0.5
                    },
                    series: {
                        marker: {
                            fillColor: 'transparent',
                            lineWidth: 0,
                            lineColor: 'transparent', // inherit from series
                            states: {
                                hover: {
                                    lineWidth: 1,
                                    radius: 4,
                                    lineColor: '#EEE',
                                    fillColor: '#FFF'
                                }
                            }
                        }
                    }
                },
                credits: {
                    enabled: false
                },
                series: [{
                        name: 'Mentions',
                        data: trendlineData
                    }]
            });
        });
    }

    $('#metrics-trend div').animate({'opacity': 1}, 500);
}

function nFormatter(num) {
    if (num > 999999)
        return (num / 1000000).toFixed(1) + 'M';
    if (num > 999)
        return (num / 1000).toFixed(1) + 'K';
    return num;
}


function loadTopSocialPlatforms() {
    streamId = window.location.href.split('#')[1].split('/')[1];
    dateFrom = $('#selected_date').attr('datefrom');
    dateTo = $('#selected_date').attr('dateto');
    language = 2;
    var pl = new SOAPClientParameters();
    pl.add("typedata", "filter");
    pl.add("streamId", streamId);
    pl.add("dateFrom", dateFrom);
    pl.add("dateTo", dateTo);
    pl.add("language", language);
    SOAPClient.invoke("http://localhost/buzzPulse/m/", "getTopSocialPlatformsData", pl, true, topSocialLoadCompleted);
}

function arraySum(array) {
    var sum = 0;
    if (array.length > 0)
        for (i = 0; i < array.length; i++)
            sum += parseInt(array[i]);
    return sum;
}

function topSocialLoadCompleted(r) {
    console.log(r);
    dname = r.name.split(';');
    data = r.data.split(';');
    trend = r.trend.split(';');
    var social = [['type', 'icon-twitter-metrics', '#00aced'],
        ['posts', 'icon-boards-metrics', '#e77800'],
        ['authors', 'icon-blogs-metrics', '#41a293'],
        ['threads', 'icon-news-metrics', '#dd4b39']];
    var dtotal = arraySum(data);
    var html = '';
    for (i = 0; i < 4; i++) {
        html += '<li class="mozaic-widget social-platform widget-platform" data-widget="platform" data-params="" data-guid="widget-2187" data-initialized="true">' +
                '<div id="graph' + i + '" style="" percent="' + parseInt(parseInt(data[i]) / dtotal * 100) + '"></div>' +
                '<div id="social-platform-twitter" class="mozaic-widget social-platform-graph widget-time_series" data-widget="time_series" data-params="" data-guid="widget-2196" data-initialized="true" data-highcharts-chart="34">' +
                '<div class="highcharts-container" id="socialtrend-' + i + '" style="position: relative; overflow: hidden; width: 100px; height: 45px; text-align: left; line-height: normal; z-index: 0; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); font-family: \'Lucida Grande\', \'Lucida Sans Unicode\', Verdana, Arial, Helvetica, sans-serif; font-size: 12px;"></div>' +
                '</div>' +
                '<div class="mozaic-widget metrics-text-link widget-item_count" data-widget="item_count" data-params="" data-guid="widget-2197" data-initialized="true">' +
                '<div>' +
                '<i class="' + social[i][1] + '"></i>' +
                '<span class="number" data-id="twitter" rel="tooltip" data-title="' + data[i] + '" data-original-title="">' +
                nFormatter(data[i]) + 
                '</span>' +
                '<span class="text">' + social[i][0] + '</span>' +
                '</div>' +
                '</div>' +
                '<div class="social-hover"></div>' +
                '<div class="platform-name-hover">' + dname[i] + '</div></li>';
    }
    $('.top-platforms').html(html);
    for (i = 0; i < 4; i++) {
        dtrend = trend[i].split(',');
        for (j = 0; j < dtrend.length; j++)
            dtrend[j] = parseInt(dtrend[j]);
        if (document.getElementById('graph' + i).childNodes.length != 0)
            $('#graph' + i).html();
        socialGraph(document.getElementById('graph' + i), 2, 2, social[i][2], 48, parseInt(parseInt(data[i])/dtotal * 100));
        $('#socialtrend-' + i).highcharts({
            chart: {
                type: 'areaspline',
                spacingBottom: 10
            },
            title: {
                text: null
            },
            legend: {
                enabled: false
            },
            xAxis: {
                gridLineWidth: 0,
                tickWidth: 0,
                lineWidth: 0,
                enabled: false,
                labels: {
                    enabled: false
                },
            },
            yAxis: {
                title: {
                    text: null
                },
                showFirstLabel: false,
                gridLineWidth: 0,
                minorGridLineWidth: 0,
                labels: {
                    enabled: false
                },
                endOnTick: false,
                maxPadding: 0
            },
            tooltip: {
                enabled: false
            },
            plotOptions: {
                area: {
                    fillOpacity: 0.5
                },
                series: {
                    marker: {
                        fillColor: 'transparent',
                        lineWidth: 1,
                        lineColor: 'transparent', // inherit from series
                        states: {
                            hover: {
                                radius: 2,
                                lineColor: '#EEE',
                                fillColor: 'transparent'
                            }
                        }
                    }
                }
            },
            credits: {
                enabled: false
            },
            series: [{
                    name: 'Mentions',
                    data: dtrend,
                    lineWidth: 0,
                    fillColor: social[i][2]
                }]
        });
    }
    $('#social_platforms').animate({'opacity': 1}, 100);
}

function loadSharingMetrics() {
    streamId = window.location.href.split('#')[1].split('/')[1];
    dateFrom = $('#selected_date').attr('datefrom');
    dateTo = $('#selected_date').attr('dateto');
    language = 2;
    var pl = new SOAPClientParameters();
    pl.add("typedata", "filter");
    pl.add("streamId", streamId);
    pl.add("dateFrom", dateFrom);
    pl.add("dateTo", dateTo);
    pl.add("language", language);
    SOAPClient.invoke("http://localhost/buzzPulse/m/", "getSharingMetricsData", pl, true, sharingMetricsLoadCompleted);
}

function sharingMetricsLoadCompleted(r) {
    if (r) {
        data = r.data.split(';');
        $('#sharing_metrics').animate({'opacity': 1}, 500);
        $('#sharing_metrics .fb-shares .number').html(data[0]);
        $('#sharing_metrics .tw-retweets .number').html(data[1]);
    }
}